import axios from 'axios';
import {handleRequest, handleResponse} from './interceptors';
import {IData} from './type';

const instance = axios.create({
  baseURL: 'api',
  timeout: 10000,
  headers: {}
});

// 添加请求拦截器
axios.interceptors.request.use(handleRequest);

// 添加响应拦截器
axios.interceptors.response.use(handleResponse);

const get = <IRes, IParams>(url: string) => {
  return (params?: IParams) => {
    return new Promise<IData<IRes>>((resolve, reject) => {
      instance({url, params, method: 'GET'})
        .then(res => {
          resolve(res.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  };
};

const post = <IRes, IBody>(url: string) => {
  return (body?: IBody) => {
    return new Promise<IData<IRes>>((resolve, reject) => {
      instance({url, data: body, method: 'POST'})
        .then(res => {
          resolve(res.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  };
};

export default {
  get,
  post
};
